package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lv
 * @date 2021/6/13 18:56
 */
@Service
public class Counter {
    @Autowired
    private RedisLock redisLock;
    @Autowired
    JedisPool jedisPool;

    public int reduce(String key) throws Exception {
        String id = UUID.randomUUID().toString();
        Jedis jedis = jedisPool.getResource();
        int data = 0;
        try{
            if(redisLock.lock(id)){
                String value = jedis.get(key);

                if (!StringUtils.isEmpty(value)&&isNumeric(value)){
                    data = Integer.valueOf(value);
                    data = data > 0 ? --data: 0;
                }
                jedis.set(key,String.valueOf(data));
            }else{
                throw new Exception("稍后再试");
            }
        }finally {
            jedis.close();
            redisLock.unlock(id);
        }
        return data;
    }
    public static boolean isNumeric(String str){
        for (int i = 0; i < str.length(); i++){
//            System.out.println(str.charAt(i));
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isNumeric("34"));
    }
}
